﻿using System;
using System.Collections.Generic;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Tabs;
using DotNetNuke.UI.WebControls;

namespace BrandonHaynes.Providers.Navigation
	{
	/// <summary>
	/// An arbitrary batch of extension methods that (hopefully) make the primary code paths more readable.  Nothing
	/// too sophisticated here.
	/// </summary>
	static class Extensions
		{
		/// <summary>
		/// Executes an action against each element in an enumeration (why isn't this in System.Linq?)
		/// </summary>
		public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
			{
			foreach (T t in sequence)
				action(t);
			}

		/// <summary>
		/// Returns the TabInfo associated with a given node
		/// </summary>
		public static TabInfo GetByNode(this Dictionary<int, TabInfo> tabs, DNNNode node)
			{
			int tabId;
			TabInfo tab;

			return int.TryParse(node.ID, out tabId) ?
				tabs.TryGetValue(tabId, out tab) ?
					tab :
					null :
				null;
			}

		/// <summary>
		/// Returns a dictionary of tabs for a given portal
		/// </summary>
		public static Dictionary<int, TabInfo> GetTabMap(int portalId)
			{ return new TabController().GetTabsByPortal(portalId); }

		/// <summary>
		/// Returns a dictionary of tabs for the current portal (as reported by GetCurrentPortalSettings()
		/// </summary>
		public static Dictionary<int, TabInfo> GetTabMap()
			{ return GetTabMap(PortalController.GetCurrentPortalSettings().PortalId); }
		}
	}
